import React, { useState, useEffect } from 'react';
import styles from '../css/photoAlbum.module.css';
import leftImg from '../assets/left.png';
import hourseImg from '../assets/hourse3.png';
import infoImg from '../assets/right.png';
import defaultImg from '../assets/pandaback.png';
import { useNavigate } from 'react-router-dom';
import { getScenicImages, getScenicTickets } from '../api/photo'; // 导入API方法
import { imgUrl } from '../config'; // 导入imgUrl
const PhotoAlbum = () => {
    const [data, setData] = useState(null);
    const [datas, setDatas] = useState(null);
    const [alertData, setAlertData] = useState(null);
    const [showAlert, setShowAlert] = useState(false);
    const [showImageAlert, setShowImageAlert] = useState(false);
    const [currentImageIndex, setCurrentImageIndex] = useState(0);
    const [images, setImages] = useState([]);
    const [alertContent, setAlertContent] = useState('');
    const [showBuyAlert, setShowBuyAlert] = useState(false);
    const [ticketData, setTicketData] = useState([]);
    const [scenicName, setScenicName] = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const navigate = useNavigate();

    const scenic_id = sessionStorage.getItem("jingid");
    const create_time = sessionStorage.getItem("create_time");

    useEffect(() => {
        const fetchData = async () => {
            try {
                setLoading(true);
                const alertdata = JSON.parse(sessionStorage.getItem("alertdata"));
                setAlertData(alertdata);

                const storedScenicName = sessionStorage.getItem('scenicName');
                if (storedScenicName) {
                    setScenicName(storedScenicName);
                }

                // 使用封装的API方法获取数据
                const [imageData, ticketData] = await Promise.all([
                    getScenicImages(scenic_id),
                    getScenicTickets(scenic_id)
                ]);

                setDatas(imageData.data);
                renderImages(imageData.data);

                // 处理门票数据
                const processedTicketData = ticketData.data.reduce((acc, item) => {
                    if (item.children && item.children.length > 0) {
                        return [...acc, ...item.children];
                    }
                    return acc;
                }, []);

                setTicketData(processedTicketData);
                setData(ticketData.data);
            } catch (err) {
                setError(err.message);
                console.error('获取数据时出错:', err);
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, [scenic_id]);

    const renderImages = (data) => {
        if (data[0]?.children === undefined) return;
        const imageList = data[0].children[0].img.split(",");
        setImages(imageList);
    };

    const handleImageClick = (index) => {
        setCurrentImageIndex(index);
        setShowImageAlert(true);
    };

    const handleReserve = (i) => {
        if (!ticketData ||!ticketData[i]) {
            console.error('Invalid ticket data at index:', i);
            return;
        }

        const reservedTicket = ticketData[i];
        console.log('Reserved Ticket:', reservedTicket);

        sessionStorage.setItem('reservedTicket', JSON.stringify(reservedTicket));
        navigate('/suborder');
    };

    const handleGobuy = (i) => {
        console.log('handleGobuy');
        if (!ticketData) return;

        const ticket = ticketData[i];
        if (!ticket) {
            console.error('Invalid ticket data at index:', i);
            return;
        }

        console.log('Ticket details:', ticket.deatils);
        setAlertContent(ticket.deatils || '暂无购买须知信息');
        setShowBuyAlert(true);
    };

    const handleBack = () => {
        window.history.back();
    };

    const handleHome = () => {
        navigate('/home');
    };

    const handleCloseImage = () => {
        setShowImageAlert(false);
    };

    const handleShowTickets = () => {
        setShowAlert(!showAlert);
        console.log("显示门票弹窗");
    };

    const handleShut = () => {
        setShowBuyAlert(false);
    };

    const handleImageError = (e, fallback) => {
        e.target.src = defaultImg;
    };

    return (
        <div className={styles.container}>
            {/* 门票弹窗 */}
            {showAlert && (
                <div className={styles.alert}>
                    <div className={styles.alertTwo} onClick={handleShowTickets}></div>
                    <div className={styles.alertOne}>
                        <div className={styles.ticketTwo}>
                            <b>门票</b>
                            <div className={styles.sold}>已售 <span id="twoes">2000</span> +</div>
                            <div className={styles.twoBlock}>
                                {ticketData.map((item, i) => (
                                    <React.Fragment key={i}>
                                        <div style={{ marginTop: '5px' }}>
                                            <div className={styles.adult}>
                                                <div>
                                                    <b>{item.name}</b>
                                                    <del>￥{item.original_price || '0.00'}</del>
                                                </div>
                                            </div>
                                            <div className={styles.day}>
                                                <div>
                                                    <span style={{ margin: '0px 10px 5px 0px', color: '#0aa1f9' }}>可订明日</span>
                                                    <p style={{ fontSize: '13px', color: '#ff5733' }}>
                                                        ￥<span style={{ fontSize: '16px' }}>{item.current_price || '0.00'}</span>
                                                        <span style={{ fontSize: '15px', color: '#535453' }}>起</span>
                                                    </p>
                                                </div>
                                            </div>
                                            <div className={styles.retreat}>
                                                <div>
                                                    <span style={{ margin: '0px 10px 5px 0px', color: '#0aa1f9' }}>随时退，无需退票</span>
                                                    <p>优惠￥10</p>
                                                </div>
                                            </div>
                                            <div className={styles.reserve}>
                                                <div>
                                                    <span
                                                        style={{ margin: '0px 10px 5px 0px', color: '#535453' }}
                                                        onClick={() => handleGobuy(i)}
                                                    >
                                                        <span>已售{item.num || 0}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                                                        购买须知<img src={infoImg} alt="" />
                                                    </span>
                                                    <p onClick={() => handleReserve(i)}>预定</p>
                                                </div>
                                            </div>
                                        </div>
                                        {i < ticketData.length - 1 && (
                                            <div style={{
                                                height: '1px',
                                                backgroundColor: '#e0e0e0',
                                                margin: '10px 0'
                                            }}></div>
                                        )}
                                    </React.Fragment>
                                ))}
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* 购买须知弹窗 */}
            {showBuyAlert && (
                <div style={{ position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', backgroundColor: 'rgba(0, 0, 0, 0.5)', zIndex: 999 }}>
                    <div style={{ position: 'fixed', bottom: 0, left: 0, width: '100%', backgroundColor: '#fff', padding: '20px', boxShadow: '0 -2px 10px rgba(0, 0, 0, 0.1)', zIndex: 1000 }}>
                        <div className={styles.alertone}>
                            <p>购买须知</p>
                            <div dangerouslySetInnerHTML={{ __html: alertContent }} />
                            <div className={styles.close} onClick={handleShut}>关闭</div>
                        </div>
                    </div>
                </div>
            )}

            {/* 图片弹窗 */}
            {showImageAlert && (
                <div className={styles.imgalert} onClick={handleCloseImage}>
                    <div className={styles.black}>
                        <p>
                            <span className={styles.ones}>{currentImageIndex + 1}</span>
                            <span className={styles.twos}>/{images.length}</span>
                        </p>
                    </div>
                    <div className={styles.borderimg}>
                        <img
                            style={{ width: '98%', height: '55vh', borderRadius: '10px' }}
                            src={`${imgUrl}${images[currentImageIndex]}`}
                            alt=""
                            onError={(e) => handleImageError(e, defaultImg)}
                        />
                    </div>
                    <div className={styles.botImg}>
                        <div style={{ display: 'flex' }}>
                            <span>上传于</span>
                            <span className={styles.timer}>{create_time}</span>
                        </div>
                        <div style={{
                            width: '10vh',
                            height: '5vh',
                            marginLeft: '10px',
                            marginTop: '5px',
                            flexDirection: 'column',
                            display: 'flex'
                        }}>
                            <p className={styles.fontSize}>{datas && datas[0].name}</p>
                            <div className={styles.linebox}></div>
                        </div>
                    </div>
                </div>
            )}

            {/* 顶部导航 */}
            <div className={styles.top}>
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    whiteSpace: 'nowrap',
                    width: '50%',
                    justifyContent: 'space-between'
                }}>
                    <div className={styles.left}>
                        <img src={leftImg} alt="" onClick={handleBack} />
                        <div className={styles.line}></div>
                        <img id="hourse" src={hourseImg} alt="" onClick={handleHome} />
                    </div>
                </div>
                <p>景区图片</p>
            </div>

            {/* 分类标题 */}
            <div className={styles.three}>
                <b className={styles.twoClassify}>
                    {datas && datas[0]? datas[0].name + ' ' : '加载中...'}
                    {images.length > 0? `${images.length}` : ''}
                </b>
            </div>

            {/* 新增文字行 */}
            <div style={{ marginLeft: '25px', fontSize: '16px', fontWeight: 'bold' }}>
                {datas && datas[0]? datas[0].name + ' ' : '加载中...'}
                {images.length > 0? `${images.length}` : ''}
            </div>

            {/* 图片列表 */}
            <div className={styles.itemImg}>
                {images.length > 0? (
                    images.map((img, index) => (
                        <img
                            key={index}
                            src={`${imgUrl}${img}`}
                            alt=""
                            onClick={() => handleImageClick(index)}
                            onError={(e) => handleImageError(e, defaultImg)}
                        />
                    ))
                ) : (
                    <p id="noneImage">暂无图片</p>
                )}
            </div>

            {/* 底部栏 */}
            <div className={styles.bottom}>
                <div className={styles.bottomLeft}>
                    <b style={{ margin: '10px 0 0 8px', color: '#535453', fontWeight: 'bold', fontSize: 'px' }}>
                        {scenicName || '景区名称'}
                    </b>
                    <p style={{ fontSize: '13px', color: '#ff5733' }}>
                        ￥<span style={{ fontSize: '16px' }}>
                            {ticketData.length > 0? ticketData[0].current_price || '0.00' : '0.00'}
                        </span>
                        <span style={{ fontSize: '15px', color: '#535453' }}>起</span>
                    </p>
                </div>
                <div className={styles.bottomRight} onClick={handleShowTickets}>
                    <p>查看门票</p>
                </div>
            </div>
        </div>
    );
};

export default PhotoAlbum;    